package system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import common.model.enums.SpecialRoleEnum;
import common.model.po.SysTopic;
import common.model.po.SysTopicComment;
import common.model.po.SysUser;
import common.model.request.SendEmailRequest;
import common.model.request.base.PaginationRequest;
import common.model.response.base.Result;
import common.util.EmailTemplateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import system.mapper.SysTopicMapper;
import system.model.converter.SysTopicConverter;
import system.model.request.ModifyTopicSortRequest;
import system.model.request.SaveTopicRequest;
import system.model.request.SearchTopicRequest;
import system.model.request.ToggleTopicClosedRequest;
import system.model.vo.SysTopicVo;
import system.service.MailService;
import system.service.SysTopicCommentService;
import system.service.SysTopicService;
import system.service.SysUserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author 米泽鹏
 * @since 2023-08-29 上午 12:15
 */
@Service
public class SysTopicServiceImpl extends ServiceImpl<SysTopicMapper, SysTopic> implements SysTopicService {

	@Resource
	private SysTopicMapper mapper;
	@Resource
	private SysTopicCommentService messageReplyService;
	@Resource
	private SysUserService userService;
	@Resource
	private MailService mailService;

	@Override
	public Page<SysTopicVo> pageSysTopic(PaginationRequest<SearchTopicRequest, SysTopic> paginationRequest) {
		return mapper.pageSysTopic(paginationRequest.buildPage(), paginationRequest.getParams());
	}

	@Override
	public Result<?> saveTopic(SaveTopicRequest request) {
		SysTopic topic = SysTopicConverter.saveRequestToPo(request);
		if (topic.getId() == null) {
			save(topic);
		} else {
			updateById(topic);
		}
		// 邮件通知最高管理员
		SysUser topicUser = userService.getById(topic.getUserId());
		List<SysUser> masters = userService.getUsersByRoleCode(SpecialRoleEnum.MASTER.getRoleCode());
		// 如果发布新话题的是最高管理员，则不邮件通知
		if (masters.stream().noneMatch(master -> topicUser.getId().equals(master.getId()))) {
			List<String> emails = masters.stream().map(SysUser::getEmail).filter(StrUtil::isNotBlank).collect(Collectors.toList());
			if (!emails.isEmpty()) {
				SendEmailRequest sendEmailRequest = new SendEmailRequest();
				sendEmailRequest.setToList(emails);
				sendEmailRequest.setSubject((request.getId() == null ? "新增" : "更新") + "话题【幸福工厂游戏工具网站】");
				sendEmailRequest.setText(request.getId() == null ? EmailTemplateUtil.getNewTopicContent(topic.getTitle(), topic.getContent(), topicUser.getUsername(), topic.getNickname()) : EmailTemplateUtil.getUpdateTopicContent(topic.getTitle(), topic.getContent(), topicUser.getUsername(), topic.getNickname()));
				sendEmailRequest.setHtml(true);
				mailService.sendEmail(sendEmailRequest);
			}
		}
		return Result.success();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> deleteTopic(Long id) {
		SysTopic topic = getById(id);
		// 删除话题
		removeById(id);
		// 删除该话题的所有评论
		messageReplyService.lambdaUpdate().eq(SysTopicComment::getTopicId, id).remove();
		// 邮件通知最高管理员
		SysUser topicUser = userService.getById(topic.getUserId());
		List<SysUser> masters = userService.getUsersByRoleCode(SpecialRoleEnum.MASTER.getRoleCode());
		// 如果发布新话题的是最高管理员，则不邮件通知
		if (masters.stream().noneMatch(master -> topicUser.getId().equals(master.getId()))) {
			List<String> emails = masters.stream().map(SysUser::getEmail).filter(StrUtil::isNotBlank).collect(Collectors.toList());
			if (!emails.isEmpty()) {
				SendEmailRequest sendEmailRequest = new SendEmailRequest();
				sendEmailRequest.setToList(emails);
				sendEmailRequest.setSubject("删除话题【幸福工厂游戏工具网站】");
				sendEmailRequest.setText(EmailTemplateUtil.getDeleteTopicContent(topic.getTitle(), topic.getContent(), topicUser.getUsername(), topic.getNickname()));
				sendEmailRequest.setHtml(true);
				mailService.sendEmail(sendEmailRequest);
			}
		}
		return Result.success();
	}

	@Override
	public Result<?> toggleTopicClosed(ToggleTopicClosedRequest request) {
		lambdaUpdate().eq(SysTopic::getId, request.getTopicId()).set(SysTopic::getIsClosed, request.getIsClosed()).update();
		return Result.success();
	}

	@Override
	public Result<?> modifyTopicSort(ModifyTopicSortRequest request) {
		lambdaUpdate().eq(SysTopic::getId, request.getTopicId()).set(SysTopic::getSort, request.getSort()).update();
		return Result.success();
	}

}
